<template>
  <div class="chart-root-wrapper" style="width: 100%">
    <div class="chart-title-wrapper">
      <div class="chart-title">打卡统计</div>
      <div class="chart-options">
        <el-form inline size="small">
          <el-form-item label="内容设置">
            <el-radio-group v-model="showTable">
              <el-radio :value="false">图表</el-radio>
              <el-radio :value="true">数值</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="科室">
            <el-checkbox-group v-model="filter.office" @change="handleRedraw">
              <el-checkbox value="管制一室">一室</el-checkbox>
              <el-checkbox value="管制二室">二室</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="时长排序">
            <el-radio-group v-model="filter.order" @change="handleRedraw">
              <el-radio :value="true">升序</el-radio>
              <el-radio :value="false">降序</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="chart-content-wrapper">
      <el-scrollbar style="width: 100%">
        <v-chart
          v-if="
            source != null &&
            !hideChart &&
            values != null &&
            showChart &&
            !showTable
          "
          :style="{ width: data.length * 60 + 200 + 'px', height: '400px' }"
          :option="option"
          ref="chart"
        />
        <el-empty
          v-if="hideChart"
          description="数据过大，已关闭图表"
        ></el-empty>
        <el-table
          v-if="source != null && showChart && showTable"
          :data="tableData"
        >
          <el-table-column
            prop="name"
            label="姓名"
            width="120"
          ></el-table-column>
          <el-table-column
            v-for="person in data"
            :prop="person.name"
            :label="person.name"
            width="120"
          ></el-table-column>
        </el-table>
      </el-scrollbar>
    </div>
    <!-- <pre>{{ values ? values.data : null }}</pre> -->
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick } from "vue";
import dayjs from "dayjs";
import useHourStore from "@/store/hour.js";
import useCommonStore from "@/store/common.js";
import fetchSectors from "./fetchSectors.js";
import { ElNotification } from "element-plus";

// import echarts
// import { use } from "echarts/core";
import * as echarts from "echarts/core";
import { SVGRenderer, CanvasRenderer } from "echarts/renderers";
import {
  BarChart,
  LineChart,
  ScatterChart,
  EffectScatterChart,
} from "echarts/charts";
import {
  LegendComponent,
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  PolarComponent,
} from "echarts/components";
import { LabelLayout, UniversalTransition } from "echarts/features";
import VChart, { THEME_KEY } from "vue-echarts";

echarts.use([
  CanvasRenderer,
  BarChart,
  TooltipComponent,
  GridComponent,
  LabelLayout,
]);

const hourStore = useHourStore();
const commonStore = useCommonStore();

const source = computed(() => hourStore.generalViewConfigs.source);

const filter = ref({
  office: ["管制一室", "管制二室"],
  order: false,
});

const showTable = ref(false);
const showChart = ref(true);
const hideChart = computed(() => {
  if (source.value == null) {
    return false;
  } else if (
    source.value.content &&
    (source.value.count > 1000 || source.value.content.length > 1000)
  ) {
    return true;
  }
});

const handleRedraw = async () => {
  showChart.value = false;
  await nextTick();
  showChart.value = true;
  // setTimeout(() => {
  //   showChart.value = true;
  // }, 500);
  // if (chart.value) {
  //   chart.value.resize();
  // }
};

const tableData = computed(() => {
  let output = [{ name: "小时数" }, { name: "见习小时" }, { name: "放单小时" }];
  for (let i = 0; i < data.value.length; i++) {
    output[0][data.value[i].name] = data.value[i].total + " 小时";
    output[1][data.value[i].name] = data.value[i].hours + " 小时";
    output[2][data.value[i].name] = data.value[i].hours2 + " 小时";
  }
  return output;
});

const values = computed(() => {
  let data = {};
  if (!source.value || !source.value.content) return null;
  source.value.content.forEach((item) => {
    let si = dayjs(item.startTime);
    let ss = dayjs(source.value.start);
    let startTime = si.isBefore(ss, "second") ? ss : si;
    let endTime = item.endTime == null ? dayjs() : dayjs(item.endTime);
    let hours = endTime.diff(startTime, "hour", true);
    if (!data[item.userName]) {
      data[item.userName] = {
        hours: 0,
        hours2: 0,
      };
    }
    if (item.seatRole == "学员") {
      data[item.userName].hours2 += hours;
    } else {
      data[item.userName].hours += hours;
    }
  });
  let labels = [];
  let values = [];
  let values2 = [];
  let data2 = [];
  Object.keys(data).forEach((key) => {
    labels.push(key);
    values.push(parseFloat(data[key].hours.toFixed(1)));
    values2.push(parseFloat(data[key].hours2.toFixed(1)));
    data2.push({
      name: key,
      hours: parseFloat(data[key].hours.toFixed(1)),
      hours2: parseFloat(data[key].hours2.toFixed(1)),
      total: parseFloat((data[key].hours + data[key].hours2).toFixed(1)),
    });
  });
  return {
    count: labels.length,
    labels,
    values,
    values2,
    data,
    data2,
  };
});

const matchOffice = (item) => {
  // try to fix error:
  // undefined (reading 'office')
  let u = source.value.users.filter((user) => user.name == item.name);
  if (u != null && u.length > 0) {
    return u[0].office;
  } else {
    console.warn(
      "[HOURS] Cannot match userName with item:",
      JSON.stringify(item, null, 2)
      // JSON.stringify(source.value.users)
    );
    return "";
  }
};

const data = computed(() => {
  let temp = values.value.data2.filter((item) =>
    filter.value.office.includes(matchOffice(item))
  );
  temp.sort(function (a, b) {
    if (filter.value.order) {
      return a.total - b.total;
    } else {
      return b.total - a.total;
    }
  });

  return temp;
});

const option = computed(() => {
  return {
    grid: {
      left: 30,
      right: 20,
      // x2: 50,
      // y2: 50,
      height: "65.6%",
    },
    tooltip: {
      show: true,
      trigger: "axis",
      axisPointer: { type: "cross" },
    },
    xAxis: {
      type: "category",
      show: true,
      data: data.value.map((item) => item.name),
    },
    yAxis: {
      id: 0,
      type: "value",
      // name: "扇区数量",
      position: "left",
      axisLine: { show: false },
      axisLabel: { show: false },
      splitLine: { show: false },
    },
    series: [
      {
        name: "小时",
        data: data.value.map((item) => item.hours),
        type: "bar",
        xAxisIndex: 0,
        yAxisIndex: 0,
        stack: "x",
        coordinateSystem: "cartesian2d",
        smooth: false,
        emphasis: false,
        label: {
          show: true,
          formatter: (item) => (item.value == 0 ? "" : item.value),
          color: commonStore.darkMode ? "#000" : "#FFF",
          textBorderColor: commonStore.darkMode
            ? "rgba(255,255,255,0.75)"
            : "rgba(0,0,0,0.75)",
          textBorderWidth: 2,
          fontSize: "16px",
          fontWeight: "bold",
          distance: 12,
        },
        lineStyle: {
          color: commonStore.darkMode
            ? "rgba(255,255,255,0.5)"
            : "rgba(0,0,0,0.3)",
          type: "dotted",
          opacity: 1,
        },
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              // color: "rgb(77, 119, 255)",
              color: "#CEE5D0",
            },
            {
              offset: 1,
              // color: "rgb(77, 119, 255)",
              color: "#57837B",
            },
          ]),
          borderRadius: 50,
        },
        clip: false,
      },
      {
        name: "见习小时",
        data: data.value.map((item) => item.hours2),
        type: "bar",
        xAxisIndex: 0,
        yAxisIndex: 0,
        stack: "x",
        coordinateSystem: "cartesian2d",
        smooth: false,
        emphasis: false,
        label: {
          show: true,
          formatter: (item) => (item.value == 0 ? "" : item.value),
          color: commonStore.darkMode ? "#000" : "#FFF",
          textBorderColor: commonStore.darkMode
            ? "rgba(255,255,255,0.75)"
            : "rgba(0,0,0,0.75)",
          textBorderWidth: 2,
          fontSize: "16px",
          fontWeight: "bold",
          distance: 12,
        },
        lineStyle: {
          color: commonStore.darkMode
            ? "rgba(255,255,255,0.5)"
            : "rgba(0,0,0,0.3)",
          type: "dotted",
          opacity: 1,
        },
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              // color: "rgb(255, 0, 135)",
              color: "#DFD3C3",
            },
            {
              offset: 1,
              // color: "rgb(135, 0, 157)",
              color: "#7D6E83",
            },
          ]),
          borderRadius: 50,
        },
        clip: false,
      },
    ],
  };
});

const chart = ref();
let resizeTimer = null;
onMounted(() => {
  resizeTimer = setInterval(() => {
    if (chart.value) {
      chart.value.resize();
    }
  }, 1000);
});

onUnmounted(() => {
  clearInterval(resizeTimer);
  resizeTimer = null;
});
</script>

<style scoped>
@import "./chartStyles.css";
</style>
